package com.maixun.lib_network.base

import com.maixun.lib_network.interceptor.CommonRequestInterceptor
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

/**
 * 作者：Lmoumou
 * 时间：2020/6/22 13:53
 */
abstract class NetworkApi {
    companion object {

        private val retrofitHashMap by lazy { hashMapOf<String, Retrofit>() }

        lateinit var iNetworkRequiredInfo: INetworkRequiredInfo
        fun init(networkRequiredInfo: INetworkRequiredInfo) {
            iNetworkRequiredInfo = networkRequiredInfo
        }
    }

    private var mOkHttpClient: OkHttpClient? = null

    protected fun <T> getRetrofit(service: Class<T>): Retrofit {
        //根据BaseUrl+ApiService缓存Retrofit
        val key = "${iNetworkRequiredInfo.getBaseUrl()}${service.name}"
        if (retrofitHashMap[key] != null) {
            return retrofitHashMap[key]!!
        }

        val retrofit = Retrofit.Builder()
            .baseUrl(iNetworkRequiredInfo.getBaseUrl())
            .client(getOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
        retrofitHashMap[key] = retrofit
        return retrofit
    }

    private fun getOkHttpClient(): OkHttpClient {
        if (mOkHttpClient == null) {
            val okHttpClientBuilder = OkHttpClient.Builder()
            if (getInterceptor() != null) {
                okHttpClientBuilder.addInterceptor(getInterceptor()!!)
            }
            val cacheSize: Long = 100 * 1024 * 1024 // 10MB
            okHttpClientBuilder.cache(
                Cache(iNetworkRequiredInfo.getApplicationContext().cacheDir, cacheSize)
            )
            okHttpClientBuilder.addInterceptor(CommonRequestInterceptor(iNetworkRequiredInfo))
            mOkHttpClient = okHttpClientBuilder.build()
        }

        return mOkHttpClient!!
    }

    protected abstract fun getInterceptor(): Interceptor?

}